package com.itheima.common;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RequestBody.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {


    @ExceptionHandler({SQLIntegrityConstraintViolationException.class})
    public R<String> exceptionHandler(SQLException ex){
        if (ex.getMessage().contains("Duplicate entry")){
            String[] s = ex.getMessage().split(" ");
            String msg=s[2]+"已存在";
           return R.error(msg);
        }
        return R.error("未知错误");
    }
    @ExceptionHandler({CategoryException.class})
    public R<String> exceptionCategor(CategoryException ex){

        return R.error(ex.getMessage());
    }
}
